package org.theonept.travian.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.theonept.travian.model.Compte;

public class ConnexionUtil extends HttpUtil {
	static Map<Long, CookieManager> cookiMap = new HashMap<Long, CookieManager>();

	public static Compte connect(Compte compte) {
		try {
			CookieManager cookieManager = new CookieManager();
			CookieHandler.setDefault(cookieManager);
			URL urlFirst = new URL(compte.getUrlServeur() + "dorf1.php");
			HttpURLConnection connectionFirst = (HttpURLConnection) urlFirst.openConnection();
			Document first = Jsoup.parse(connectionFirst.getInputStream(), connectionFirst.getContentEncoding(),
					compte.getUrlServeur());
			String login = first.getElementsByAttributeValue("name", "login").get(1).attr("value");
			String s1 = first.getElementById("s1").attr("value");

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			nameValuePairs.add(new BasicNameValuePair("name", compte.getUsername()));
			nameValuePairs.add(new BasicNameValuePair("password", compte.getPassword()));
			nameValuePairs.add(new BasicNameValuePair("w", "1680-1050"));
			nameValuePairs.add(new BasicNameValuePair("s1", s1));
			nameValuePairs.add(new BasicNameValuePair("login", login));

			connectionFirst.disconnect();
			String result = excutePost(compte.getUrlServeur() + "dorf1.php", nameValuePairs);
			Jsoup.parse(result);
			if (!getEtat(compte)) {
				compte.setState(false);
				return compte;
			}
			Compte.parseCompte(result, compte);
			compte.setState(true);
			if (compte.getIdCompte() != null) {
				cookiMap.put(compte.getIdCompte(), cookieManager);
			}

		} catch (UnknownHostException e) {
			compte.setState(false);
		}

		catch (FileNotFoundException e) {
			compte.setState(false);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return compte;
	}

	public synchronized static boolean getEtat(Compte compte) {
		Document doc = HttpUtil.getDocumentFromUrl(compte.getUrlServeur() + "dorf1.php");
		return (doc != null && doc.toString() != null && !doc.toString().contains("accountNameOrEmailAddress"));

	}

	public static void disconnect(Compte compte) {
		try {
			URL url = new URL(compte.getUrlServeur() + "logout.php");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			// Get Response
			InputStream is = connection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
			StringBuffer response = new StringBuffer();
			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			rd.close();
			connection.disconnect();
		} catch (Exception e) {

		}

	}
}
